package com.bawei.property.vm

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.property.entity.CarColorValue
import com.bawei.property.entity.CarImageEntity
import com.bawei.property.entity.ParkValue
import com.bawei.property.intent.ParkViewIntent
import com.bawei.property.model.ParkApplyRepository
import com.bawei.property.state.ParkUiState
import com.blankj.utilcode.util.GsonUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.lang.Exception
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2024/8/28
 * Desc:
 */

@HiltViewModel
class ParkViewModel @Inject constructor(private val repository: ParkApplyRepository) : BaseViewModel<ParkViewIntent>(){

    private val _uiState = MutableStateFlow<ParkUiState>(ParkUiState.NoneState)
    val uiState: StateFlow<ParkUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: ParkViewIntent) {
        when(intent){
            is ParkViewIntent.LoadParkList -> loadParkList()
            is ParkViewIntent.LoadCarColorList -> loadCarColorList()
            is ParkViewIntent.UploadCarImages -> uploadCarImage(intent.list)
            else -> {}
        }
    }

    /**
     * 多任务上传
     */
    private fun uploadCarImage(list: List<CarImageEntity>){
        viewModelScope.launch(Dispatchers.IO){
            try {
                //遍历执行
                val deferredResult = list.map {
                    async {
                        var builder = MultipartBody.Builder()
                        builder.setType(MultipartBody.FORM)
                        //将文件转成RequestBody对象
                        var body = File(it.path).asRequestBody("multipart/form-data".toMediaTypeOrNull()) //指定使用Form表单提交
                        builder.addFormDataPart("file", it.name, body)
                        var parts = builder.build().parts as MutableList<MultipartBody.Part>
                        repository.uploadCarImages(parts)
                    }
                }

                //等待所有任务执行完
                var results = deferredResult.awaitAll()
                Log.i("==============", "uploadCarImage Result：${GsonUtils.toJson(results)}")

                var allUploadSuccess = false
                var imgUrls = mutableListOf<String>()
                results.forEachIndexed { index, entity ->
                    if(entity.statuesCode == "200"){
                        allUploadSuccess = true
                        imgUrls.add("http://10.161.9.80:7035/${list[index].name}")
                    } else{
                        allUploadSuccess = false
                    }
                }

                //发送UI状态，通知View是否上传成功
                if (allUploadSuccess){
                    _uiState.value = ParkUiState.UploadImageSuccess(imgUrls)
                }else{
                    _uiState.value = ParkUiState.UploadImageFail("上传失败")
                }
            } catch (e: Exception){
                e.printStackTrace()
            } finally {
                cancel()
            }
        }
    }

    private fun loadCarColorList() {
        viewModelScope.launch(Dispatchers.IO){
            try {
                var result = repository.getCarColorList()
                if (result.statuesCode == "200"){
                    var parkList = mutableListOf<CarColorValue>()
                    parkList.addAll(result.getValues())
                    _uiState.value = ParkUiState.LoadColorListSuccess(parkList)
                } else {
                    _uiState.value = ParkUiState.LoadColorListFail(result.msg ?: "接口加载失败！")
                }
            } catch (e: Exception){
                e.printStackTrace()
                _uiState.value = ParkUiState.LoadColorListFail("接口异常，请联系客服！")
            } finally {
                cancel()
            }
        }
    }

    private fun loadParkList() {
        viewModelScope.launch(Dispatchers.IO){
            try {
                var result = repository.getParkApplyList()
                if (result.statuesCode == "200"){
                    var parkList = mutableListOf<ParkValue>()
                    parkList.addAll(result.getValues())
                    _uiState.value = ParkUiState.LoadParkListSuccess(parkList)
                } else {
                    _uiState.value = ParkUiState.LoadParkListFail(result.msg ?: "接口加载失败！")
                }
            } catch (e: Exception){
                e.printStackTrace()
                _uiState.value = ParkUiState.LoadParkListFail("接口异常，请联系客服！")
            } finally {
                cancel()
            }
        }
    }


}